//
//  XMHomePageEditView.m
//  XMJJ_zml
//
//  Created by apple on 2025/5/13.
//

#import "XMHomePageEditView.h"
#import "XMDateSelectView.h"
#import "XMintroEditView.h"
#import "UIAlertController+Extension.h"

@interface XMHomePageEditView ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *tbl;
@property (nonatomic, strong) UIImageView *avatarImgView;
@property (nonatomic, strong) XMDateSelectView *dateSelectView;
@property (nonatomic, strong) XMintroEditView *introEditView;

@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *subTitleArr;

@end

@implementation XMHomePageEditView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navTitleLabel.text = @"编辑主页";
    _titleArr = @[@"名字", @"ID号", @"简介", @"性别", @"生日", @"地区", @"学校", @"职业"];
    _subTitleArr = @[@"芝麻盐儿用户", @"283787387287", @"有趣的简介可以吸引粉丝", @"男", @"1993/08/19", @"保定", @"北京大学", @"认证更有说服力"];
    [self addSubview:self.tbl];
}

- (void)confirmAction:(UIButton *)button {
    if (self.delegate && [self.delegate respondsToSelector:@selector(confirmChange)]) {
        [self.delegate confirmChange];
    }
}

- (void)setContentWithUserInfo:(XMUserInfoModel *)userInfoModel {
    if (!userInfoModel.nickname) {
        userInfoModel.nickname = @"";
    }
    if (!userInfoModel.idNo) {
        userInfoModel.idNo = @"";
    }
    if (!userInfoModel.dsc) {
        userInfoModel.dsc = @"";
    }
    if (!userInfoModel.experience) {
        userInfoModel.experience = @"";
    }
    if (!userInfoModel.sex) {
        userInfoModel.sex = @"";
    }
    if (!userInfoModel.school) {
        userInfoModel.school = @"";
    }
    if (!userInfoModel.avatar) {
        userInfoModel.avatar = @"";
    }
    NSString *areaStr = @"";
    if (userInfoModel.province && userInfoModel.province.length > 0) {
        areaStr = userInfoModel.province;
    }
    if (userInfoModel.city && userInfoModel.city.length > 0) {
        areaStr = [areaStr stringByAppendingFormat:@"-%@", userInfoModel.city];
    }
    [_avatarImgView sd_setImageWithURL:[NSURL URLWithString:userInfoModel.avatar]];
    _subTitleArr = @[userInfoModel.nickname, userInfoModel.idNo, userInfoModel.dsc, @[@"女", @"男"][[userInfoModel.sex intValue]], userInfoModel.nickname, areaStr, userInfoModel.school, userInfoModel.nickname];
    [_tbl reloadData];
}

- (void)setSelectImg:(NSString *)imgStr {
    [_avatarImgView sd_setImageWithURL:[NSURL URLWithString:imgStr]];
}

- (void)avatarSelect:(UITapGestureRecognizer *)tap {
    XMWeakSelf;
    UIAlertController *alertVC = [UIAlertController initwithTitle:@"选择图片" message:@"" titles:@[@"相册", @"相机"] cancelTitle:@"取消" alertStyle:UIAlertControllerStyleActionSheet itemSelect:^(NSInteger selectIndex) {
        switch (selectIndex) {
            case 0: {
                [weakSelf selectImgFromeLibrary];
            }
                break;
            case 1: {
                [weakSelf selectImgFromCamera];
            }
                break;
                
            default:
                break;
        }
    }];
    [self.viewController presentViewController:alertVC animated:YES completion:^{
        
    }];
}

//相册
- (void)selectImgFromeLibrary {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerVC.delegate = self;
        [self.viewController presentViewController:pickerVC animated:YES completion:^{
            
        }];
    }
}

//相机
- (void)selectImgFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        pickerVC.delegate = self;
        [self.viewController presentViewController:pickerVC animated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [self.viewController dismissViewControllerAnimated:YES completion:nil];
    UIImage *selectImg = [info valueForKey:UIImagePickerControllerOriginalImage];
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateAvatarWithImg:)]) {
        [self.delegate updateAvatarWithImg:selectImg];
    }
}

#pragma mark - Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScaleWidth(44.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellName = @"XMHomePageEditCellName";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
        cell.textLabel.font = KFontSize(17.0);
        cell.textLabel.textColor = kColorHEX(0x333333);
        cell.detailTextLabel.font = KFontSize(15.0);
        cell.detailTextLabel.textColor = kColorHEX(0x666666);
    }
    if (indexPath.row == 1) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = _titleArr[indexPath.row];
    cell.detailTextLabel.text = _subTitleArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 4) {
        [self addSubview:self.dateSelectView];
        [_dateSelectView show];
    }
    else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(itemSelect:)]) {
            [self.delegate itemSelect:indexPath.row];
        }
    }
}

#pragma mark - Init
- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - kNavagationBarH)];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        _tbl.separatorColor = kColorHEX(0xF1F1F1);
        _tbl.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tbl.backgroundColor = kColorHEX(0xF0F0F0);
//        [_tbl registerClass:<#(nullable Class)#> forCellReuseIdentifier:<#(nonnull NSString *)#>];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
        
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(152.0))];
        headView.backgroundColor = kColorHEX(0xffffff);
        
        [headView addSubview:self.avatarImgView];
        UILabel *explainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _avatarImgView.maxY, headView.width, KScaleWidth(37.0)) font:KFontSize(15.0) textColor:kColorHEX(0x666666) textAlignment:NSTextAlignmentCenter];
        explainLabel.text = @"点击修改头像";
        [headView addSubview:explainLabel];
        
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(100.0))];
        footView.backgroundColor = kColorHEX(0xF0F0F0);
        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KBoldFontSize(17.0) frame:CGRectMake((footView.width - KScaleWidth(320.0))/2, KScaleWidth(42.0), KScaleWidth(320.0), KScaleWidth(44.0)) title:@"确定" titleColor:kColorHEX(0x333333)];
        [confirmBtn setGradientLayerWithLocations:@[@(0), @(1.0f)] colors:@[(__bridge id)kColorHEX(0xFFD800).CGColor, (__bridge id)kColorHEX(0xFFE44E).CGColor] startPoint:CGPointMake(0.5, 0.37) endPoint:CGPointMake(0.03, 0.37)];
        [confirmBtn setCornerRadius:confirmBtn.height/2];
        [confirmBtn addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:confirmBtn];
        
        _tbl.tableHeaderView = headView;
        _tbl.tableFooterView = footView;
    }
    return _tbl;
}

- (UIImageView *)avatarImgView {
    if (!_avatarImgView) {
        _avatarImgView = [[UIImageView alloc] initWithFrame:CGRectMake((self.width - KScaleWidth(70.0))/2, KScaleWidth(32.0), KScaleWidth(70.0), KScaleWidth(70.0))];
        [_avatarImgView setCornerRadius:_avatarImgView.height/2];
        _avatarImgView.userInteractionEnabled = YES;
        _avatarImgView.image = ImageNamed(@"mine_avatar_icon");
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarSelect:)];
        [_avatarImgView addGestureRecognizer:tap];
    }
    return _avatarImgView;
}

- (XMDateSelectView *)dateSelectView {
    if (!_dateSelectView) {
        _dateSelectView = [[XMDateSelectView alloc] initWithFrame:self.bounds];
        _dateSelectView.backgroundColor = [UIColor clearColor];
        _dateSelectView.dateType = XMDateDateType;
        XMWeakSelf; //生日选择
        _dateSelectView.dateSelectBlock = ^(NSString * _Nonnull selectDateStr) {
            
        };
    }
    return _dateSelectView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
